package util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhanglinfeng
 * @date create in 2023/7/18 11:29
 */
public class XmlUtil {

    public static Map<String, String> parseXml(String xml) throws Exception {
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        return root.elements().stream().collect(Collectors.toMap(Element::getName, Element::getText));
    }

    /**
     * 字符串转对象
     *
     * @param xml 待转字符串
     * @param cls class
     * @return T
     */
    public static <T> T toObject(String xml, Class<T> cls) throws Exception {
        //TODO 简化
        Map<String, String> map = parseXml(xml);
        return JsonUtil.toObject(JsonUtil.toString(map), cls);
    }

    /**
     * 字符串转对象,需要注解   XmlRootElement、 XmlElement
     *
     * @param xml 待转字符串
     * @param cls class
     * @return T
     */
    public static <T> T toObjectWithAnnotation(String xml, Class<T> cls) throws Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(cls);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        StringReader reader = new StringReader(xml);
        return (T) unmarshaller.unmarshal(reader);
    }
}
